package book.web;

import book.domain.City;
import book.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

/**
 * city 控制层
 * @author guo
 */
@Controller
@RequestMapping(value = "/city")
public class CityController {




    /*  经过测试，webflux的同步视图跳转有问题。。。暂时建议只是用rest接口 */




    private static final String CITY_FORM_PATH_NAME = "cityForm";
    private static final String CITY_LIST_PATH_NAME = "cityList";
    private static final String REDIRECT_TO_CITY_URL = "redirect:/city";

    @Autowired
    private CityService cityService;

    @GetMapping()
    public Mono<String> getCityList(final Model model) {
        model.addAttribute("cityList", cityService.findAll());
//        return CITY_LIST_PATH_NAME;
        return Mono.create(monoSink -> monoSink.success(CITY_LIST_PATH_NAME));
    }

    @GetMapping("create")
    public String createCityForm(final Model model) {
        model.addAttribute("city", new City());
        model.addAttribute("action", "create");
        return CITY_FORM_PATH_NAME;
    }

    @PostMapping("create")
    public Mono<String> postCity(@ModelAttribute City city,final Model model) {
        cityService.insertByCity(city);
//        return REDIRECT_TO_CITY_URL;
//        return Mono.create(monoSink -> monoSink.success(REDIRECT_TO_CITY_URL));
        model.addAttribute("cityList", cityService.findAll());
        return Mono.create(monoSink -> monoSink.success(CITY_LIST_PATH_NAME));
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String getCity(@PathVariable Long id, final Model model) {
        final Mono<City> city = cityService.findById(id);
        model.addAttribute("city", city);
        model.addAttribute("action", "update");
        return CITY_FORM_PATH_NAME;
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String putBook(@ModelAttribute City city) {
        cityService.update(city);
        return REDIRECT_TO_CITY_URL;
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String deleteCity(@PathVariable Long id) {
        cityService.delete(id);
        return CITY_LIST_PATH_NAME;
    }

//    @PostMapping("add")
//    @ResponseBody
//    public Mono<City> add(City city){
//        return cityService.insertByCity(city);
//    }
//
//    @PostMapping("create")
//    public String create(City city) {
//        cityService.insertByCity(city);
//        return "redirect:/list";
//    }
}
